﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using System.Threading;

namespace Brain.Editor
{
    public class DefaultEditorPluginManager : IEditorPluginManager
    {
        public List<LoadPlugin> PluginTypes { get; set; }

        public DefaultEditorPluginManager()
        {
            PluginTypes = new List<LoadPlugin>();
        }

        public void HandleAssemblies(string rootFolder, FileInfo[] files)
        {
#if !WINDOWS_PHONE
            this.PluginTypes.Clear();
            this.PluginTypes = new List<LoadPlugin>();
            for (int i = 0; i < files.Length; i++)
            {
                FileInfo info = files[i];
                if (info.FullName.ToLower().EndsWith(".dll"))
                {
#if WINDOWS
                    Assembly ass = Assembly.LoadFile(info.FullName);
#else

                    Assembly ass = Assembly.LoadFrom(info.FullName);
#endif
                    if (ass != null)
                    {
                        Type[] types = ass.GetTypes();
                        foreach (Type type in types)
                        {
                            if (!type.IsInterface)
                            {
                                Type[] inter = type.GetInterfaces();
                                foreach (Type t in inter)
                                {
                                    if (t == typeof(IEditorPlugin))
                                    {
                                        LoadPlugin load = new LoadPlugin();
                                        load.PluginType = type;
                                        load.PluginAssemblyPath = PathUtil.MakeRelative(rootFolder, info.FullName);
                                        PluginTypes.Add(load);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
#endif
        }
    }
}
